package server

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// HttpContext http 上下文环境，用于封装http读取请求参数，以及返回值的结构体
type HttpContext struct {
	R *http.Request
	W http.ResponseWriter
}

// ReadJson 读取请求中Body中参数，并转化成相应的json对象
func (c *HttpContext) ReadJson(data interface{}) error {

	//这里只能读取一次Body的数据
	body, err := io.ReadAll(c.R.Body)
	if err != nil {
		return err
	}
	return json.Unmarshal(body, data)
}

func (c *HttpContext) ReadQueryURI(data interface{}) error {
	values := c.R.URL.Query()
	valuesByte, err := json.Marshal(values)
	if err != nil {
		return err
	}
	return json.Unmarshal(valuesByte, data)
}

func (c *HttpContext) WriteJson(status int, message string, data interface{}) error {
	c.W.WriteHeader(status)
	resBody := &ResponseBody{
		Code:    status,
		Message: message,
		Data:    &data,
	}
	resBytes, err := json.Marshal(resBody)
	if err != nil {
		return err
	}
	c.W.Write(resBytes)
	return nil
}

// ResponseBody 定义通用的返回结果
type ResponseBody struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type RequestBody struct {
	data interface{}
}

// RouteBaseOnMap 逻辑运行的结构体
type RouteBaseOnMap struct {
	handlers map[string]func(ctx *HttpContext)
}

func (r *RouteBaseOnMap) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	key := r.key(req.Method, req.URL.Path)
	handler := r.handlers[key]
	if handler != nil {
		c := HttpContextFactory(w, req)
		handler(c)
	} else {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("not any router match"))
	}

}

// 将请求方法与请求路径进行拼接，作为路由的key
func (r *RouteBaseOnMap) key(method string, path string) string {
	return fmt.Sprintf("%s#%s", method, path)
}
